package com.up.vms.interfaces.rest.controller;

import com.up.vms.application.service.VideoApplicationService;
import com.up.vms.domain.module.VideoDTO;
import com.up.vms.domain.vm.entity.Video;
import com.up.vms.domain.vm.enums.VideoRecommendFlag;
import com.up.vms.domain.vm.enums.VideoStatus;
import com.up.vms.infrastructure.constants.EmpAPIConstants;
import com.up.vms.infrastructure.mvc.BaseResponse;
import com.up.vms.infrastructure.mvc.GeneRespDTO;
import com.up.vms.infrastructure.mvc.RespCode;
import com.up.vms.infrastructure.mvc.ReturnCode;
import com.up.vms.infrastructure.util.CommonUtils;
import com.up.vms.interfaces.rest.request.OpVideoRequest;
import com.up.vms.interfaces.rest.request.OperationStatusRequest;
import com.up.vms.interfaces.rest.request.VideoIdRequest;
import com.up.vms.interfaces.rest.request.VideoSaveRequest;
import com.up.vms.interfaces.rest.response.CommonResponse;
import com.up.vms.interfaces.rest.component.QnOssManager;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@Api(value = "视频管理接口", produces = "application/json")
@RequestMapping(EmpAPIConstants.API_ROOT)
@Slf4j
public class VideoController {

    @Autowired
    private VideoApplicationService videoApplicationService;

    @Autowired
    private QnOssManager qnOssManager;

    @Value("${vms.qiniu.temp.bucket}")
    private String tempBucket;

    @RequestMapping(value = "/video/list", method = RequestMethod.GET)
    @ApiOperation(value = "获取当前类型下的活动列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "index", value = "页码", dataType = "Integer"),
            @ApiImplicitParam(name = "size", value = "每页记录数", dataType = "Integer")
    })
    @ResponseBody
    public BaseResponse videoList(
            @RequestParam(value = "videoName", required = false) String videoName,
            @RequestParam(value = "status", required = false) Integer showVideoMode,
            @RequestParam(value = "categoryId", required = false) Long categoryId,
            @RequestParam(value = "index") Integer index,
            @RequestParam(value = "size") Integer size) {
        GeneRespDTO<HashMap> geneRespDTO = null;
        CommonResponse commonResponse = new CommonResponse();
        VideoDTO videoDTO = new VideoDTO();

        try {
            if (CommonUtils.isNotNull(index)) {
                videoDTO.setPage(index);
            }
            if (CommonUtils.isNotNull(size)) {
                videoDTO.setSize(size);
            }
            if (CommonUtils.isNotNull(videoName)) {
                videoDTO.setVideoName(videoName);
            }
            if (CommonUtils.isNotNull(showVideoMode)) {
                videoDTO.setShowVideoMode(showVideoMode);
            }
            if (CommonUtils.isNotNull(categoryId)) {
                videoDTO.setCategoryId(categoryId);
            }

            videoDTO.setSortColumn("created");

            geneRespDTO = videoApplicationService.getVideoList(videoDTO);

            commonResponse.setData(geneRespDTO.getData());
            commonResponse.setRespCode(new RespCode(ReturnCode.SUCCESS));

        } catch (Exception e) {
            log.error("获取活动列表失败：{}", e.getMessage(), e.getCause());
            commonResponse.setRespCode(new RespCode(ReturnCode.SERVICE_ERROR));
        }

        return commonResponse;
    }

    @RequestMapping(value = "/video/{id}", method = RequestMethod.GET)
    @ResponseBody
    public BaseResponse getById(@PathVariable(value = "id") Long id) {

        CommonResponse response = new CommonResponse();

        try {
            GeneRespDTO geneRespDTO = videoApplicationService.queryById(id);

            response.setRespCode(geneRespDTO.getRespCode());
            response.setData(geneRespDTO.getData());

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            response.setRespCode(new RespCode(ReturnCode.SERVICE_ERROR));
        }

        return response;
    }



    @RequestMapping(value = "/video/delete", method = RequestMethod.POST)
    @ResponseBody
    public BaseResponse delete(@RequestBody VideoIdRequest request) {

        CommonResponse response = new CommonResponse();
        try {
            List<String> idList = new ArrayList<>();

            if (CommonUtils.isNull(request.getId())) {
                throw new Exception("categoryId is null");
            }

            String id = request.getId();
            if (id.contains(",")) {
                String[] cs = id.split(",");
                for (String s : cs) {
                    idList.add(s);
                }
            } else{
                idList.add(id);
            }

            GeneRespDTO geneRespDTO = videoApplicationService.delete(idList);

            response.setRespCode(geneRespDTO.getRespCode());
            response.setData(geneRespDTO.getData());
        } catch (Exception ex) {
            log.error(ex.getMessage());
            response.setRespCode(new RespCode(ReturnCode.SERVICE_ERROR.getCode(), ex.getMessage()));
        }

        return response;

    }

    @RequestMapping(value = "/video/save", method = RequestMethod.POST)
    @ResponseBody
    public BaseResponse saveVideo(@RequestBody VideoSaveRequest request
                                  ) throws Exception {
        CommonResponse response = new CommonResponse();

        try {
            GeneRespDTO<Video> geneRespDTO = null;

            Video video = new Video();

            Long id = request.getId();

            video = convertFromRequest(request);

            geneRespDTO = videoApplicationService.saveVideo(video);

//            geneRespDTO = videoApplicationService.uploadFile();

            response.setRespCode(geneRespDTO.getRespCode());
            response.setData(geneRespDTO.getData());
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            response.setRespCode(new RespCode(ReturnCode.SERVICE_ERROR));
        }

        return response;
    }

    private Video convertFromRequest(VideoSaveRequest request) {

        Video video = new Video();
        if (request == null) {
            return video;
        }

        if (CommonUtils.isNotNull(request.getId())) {
            video.setId(request.getId());
        }

        if (CommonUtils.isNotNull(request.getVideoName())) {
            video.setVideoName(request.getVideoName());
        }
        if (CommonUtils.isNotNull(request.getCategoryId())) {
            video.setCategoryId(request.getCategoryId());
        }
        if (CommonUtils.isNotNull(request.getShowMode())) {
            video.setShowMode(request.getShowMode());
        } else {
            video.setShowMode(0);
        }
        if (CommonUtils.isNotNull(request.getRecommendFlag())) {
            video.setRecommendFlag(request.getRecommendFlag());
        } else {
            video.setRecommendFlag(VideoRecommendFlag.UNRECOMMEND.code);
        }
        if (CommonUtils.isNotNull(request.getSorting())) {
            video.setSorting(request.getSorting());
        } else {
            video.setSorting(0);
        }

        video.setVideoDesc(request.getVideoDesc());
        video.setVideoUrl(request.getVideoUrl());

        if (CommonUtils.isNotNull(request.getShowVideoMode())) {
            video.setShowVideoMode(request.getShowVideoMode());
        } else {
            video.setShowVideoMode(VideoStatus.HIDE.code);
        }

        if (CommonUtils.isNotNull(request.getShowImage())) {
            video.setShowImage(request.getShowImage());
        }

        return video;
    }

    @RequestMapping(value = "/image/upload", method = RequestMethod.POST)
    @ResponseBody
    public BaseResponse saveImageFile(@RequestParam(value = "upfile") MultipartFile upfile) {
        CommonResponse commonResponse = new CommonResponse();
        try {
            if (!upfile.isEmpty()) {
                String originalFileName = upfile.getOriginalFilename();
                String ct = upfile.getContentType();
                String fileTypeStr = "";
                if (ct.indexOf("/")>0) {
                    fileTypeStr = ct.substring(ct.indexOf("/") + 1);
                }

                int fileType = qnOssManager.getFileType(upfile.getOriginalFilename());
                Map map = qnOssManager.saveFileToQiniu(upfile.getInputStream(), fileType, originalFileName, fileTypeStr,null);//调用七牛云上传的方法，这里大家改成自己上传的方法

                commonResponse.setRespCode(new RespCode(ReturnCode.SUCCESS));
                commonResponse.setData(map);
            }
        } catch (Exception e) {
            commonResponse.setRespCode(new RespCode(ReturnCode.SERVICE_ERROR.getCode(), e.getMessage()));
        }

        return commonResponse;
    }

    @RequestMapping(value = "/video/upToken", method = RequestMethod.GET)
    @ResponseBody
    public BaseResponse upToken(@RequestParam(value = "bucket", required = false) String bucket) {
        CommonResponse commonResponse = new CommonResponse();
        try {
            if (CommonUtils.isNull(bucket)) {
                bucket = tempBucket;
            }
            String upToken = qnOssManager.upToken(bucket);

            Map<String, Object> map = new HashMap();
            map.put("token", upToken);

            commonResponse.setData(map);
            commonResponse.setRespCode(new RespCode(ReturnCode.SUCCESS));
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            commonResponse.setRespCode(new RespCode(ReturnCode.SERVICE_ERROR.getCode(), e.getMessage()));
        }
        return commonResponse;
    }

    @RequestMapping(value = "/video/upload", method = RequestMethod.POST)
    @ResponseBody
    public BaseResponse saveVideoFile(@RequestParam MultipartFile upfile) {
        CommonResponse commonResponse = new CommonResponse();
        log.info("video upload begin");
        try {
            if (!upfile.isEmpty()) {
                String originalFileName = upfile.getOriginalFilename();
                String ct = upfile.getContentType();
                String fileTypeStr = "";
                if (ct.indexOf("/")>0) {
                    fileTypeStr = ct.substring(ct.indexOf("/") + 1);
                }

                int fileType = 1;
                Map<String, Object> map = qnOssManager.saveFileToQiniu(upfile.getInputStream(), fileType, originalFileName, fileTypeStr,null);//调用七牛云上传的方法，这里大家改成自己上传的方法

                commonResponse.setRespCode(new RespCode(ReturnCode.SUCCESS));
                commonResponse.setData(map);
            }
            log.info("video upload success");
        } catch (Exception e) {
            commonResponse.setRespCode(new RespCode(ReturnCode.SERVICE_ERROR.getCode(), e.getMessage()));
            log.info("video upload error");
        }

        return commonResponse;
    }

    @RequestMapping(value = "/video/pfop", method = RequestMethod.POST)
    @ResponseBody
    public BaseResponse operateVideoFile(@RequestBody OpVideoRequest request) {
        CommonResponse commonResponse = new CommonResponse();
        try {
            if (CommonUtils.isNotNull(request.getKey())) {
                Map<String, Object> map = qnOssManager.operateFile(request.getKey());
                commonResponse.setData(map);
                commonResponse.setRespCode(new RespCode(ReturnCode.SUCCESS));
            } else {
                commonResponse.setRespCode(new RespCode(ReturnCode.SERVICE_ERROR.getCode(), "key is null"));
            }
        } catch (Exception e) {
            commonResponse.setRespCode(new RespCode(ReturnCode.SERVICE_ERROR.getCode(), e.getMessage()));
        }

        return commonResponse;
    }

    @RequestMapping(value = "/video/pfop/notify", method = RequestMethod.POST)
    @ResponseBody
    public BaseResponse pfopNotify(@RequestBody OperationStatusRequest request) {
        CommonResponse commonResponse = new CommonResponse();

        try {
            log.info("qiniu pfop callback begin");

            if (CommonUtils.isNotNull(request.getCode()) && request.getCode() == 0) {
                qnOssManager.deleteFile(request.getInputBucket(), request.getInputKey());
            }

            commonResponse.setRespCode(new RespCode(ReturnCode.SUCCESS));
            log.info("qiniu pfop callback finished");

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            commonResponse.setRespCode(new RespCode(ReturnCode.SERVICE_ERROR));
        }

        return commonResponse;
    }

    @RequestMapping(value = "/video/pfop/status", method = RequestMethod.GET)
    @ResponseBody
    public BaseResponse pfopStatus(@RequestParam(value = "id") String id) {
        CommonResponse commonResponse = new CommonResponse();
        List<String> idList = new ArrayList<>();

        if (id.contains(";")) {
            String[] ids = id.split(";");
            for (String pId : ids) {
                idList.add(pId);
            }
        } else {
            idList.add(id);
        }

        List<Map<String, Object>> retList = new ArrayList<>();
        for (String pId : idList) {
            Map<String, Object> map = new HashMap();
            try {
                map = qnOssManager.pfopStatus(pId);
            } catch (Exception e) {
                map.put("persistentId", pId);
                map.put("status", e.getMessage());
            }
            retList.add(map);
        }

        commonResponse.setRespCode(new RespCode(ReturnCode.SUCCESS));
        commonResponse.setData(retList);

        return commonResponse;
    }
}
